/*
 * dispatcher.c
 *
 *  Created on: Dec 13, 2011
 *      Author: piotrek
 */

#include "dispatcher.h"

void* start_dispatcher(void* args)
{

	key_t queue_key = (key_t)DISPATCHER_KEY;
	int req_queue_id = msgget(queue_key, IPC_CREAT | 0666 );
	char msg[sizeof(struct monitoring_req)];
	ssize_t rcv_bytes;

	if( req_queue_id < 0 )
	{
		LOG_MSG("Cannot create/open a dispatcher request queue.");
		return NULL;
	}

	LOG_MSG("Listening for incoming requests");

	while( (rcv_bytes = msgrcv(req_queue_id, msg, sizeof(msg), 0, 0 )) == sizeof(msg) )
	{
		struct monitor_thread *monitor_thread = (struct monitor_thread*)malloc( sizeof( struct monitor_thread ) );
		memcpy( &(monitor_thread->monitoring_req), msg, rcv_bytes);

		if( monitor_thread->monitoring_req.pid_to_be_monitored == NULL_PID )
		{
			LOG_MSG( "Creating a system monitor" );

			if(pthread_create( &(monitor_thread->thread_id), NULL, system_memory_monitoring_t_handler, monitor_thread ))
			{
				LOG_MSG("Cannot create a thread for a system monitoring!");
				continue;
			}
		}
		else
		{
			char tmp[255];
			sprintf(tmp, "Creating a process monitor for pid: %d", monitor_thread->monitoring_req.pid_to_be_monitored);

			LOG_MSG( tmp );

			if(pthread_create( &(monitor_thread->thread_id), NULL, process_memory_monitoring_t_handler, monitor_thread ))
			{
				LOG_MSG("Cannot create a thread for a process monitoring!");
				continue;
			}

		}

		append_monitor_thread(monitor_thread);

	}

	LOG_MSG( "Dispatcher finished..." );

	return NULL;
}
